package com.pzr.soccer.config.resourceServer;


import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class ExtractAuthenticationConverter extends DefaultUserAuthenticationConverter {

    /**
     * 这个方法重新定义了安全上下文 securityContextHolder.getContext.getPrincipal 返回的信息；
     * 默认只返回用户名
     * 这里添加了返回用户id
     * 方法在资源服务器起作用
     *
     * @param map
     * @return
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        String username = "username";
        String id = "id";
        //String loginType = "loginType";
        String mobile="mobile";
        String email="email";
        Map<String, Object> principal = new HashMap<>();
        if (map.containsKey(username)) {
            principal.put(username, map.get(username));
        }
        if (map.containsKey(id)) {
            principal.put(id, map.get(id));
        }
        if (map.containsKey(mobile)) {
            principal.put(mobile, map.get(mobile));
        }
        if (map.containsKey(email)) {
            principal.put(mobile, map.get(email));
        }

        Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
        return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
    }

    //从源码复制过来的
    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        if (!map.containsKey(AUTHORITIES)) {
            return List.of();
        }
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
                    .collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }

}
